import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import { hashPassword } from '../utils/crypto';
import type Tenant from './Tenant.model';
import type Department from './Department.model';
import type Role from './Role.model';

class User extends Model {
  public id!: string;
  public tenantId!: string | null;
  public departmentId?: string | null;
  public email!: string;
  public passwordHash!: string;
  public password?: string; // 临时字段，用于设置密码
  public firstName?: string;
  public lastName?: string;
  public type!: string;
  public status!: string;
  public roleId!: string | null;
  public avatar?: string;
  public lastLoginAt?: Date;
  public lastLoginIp?: string;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public deletedAt?: Date;

  // 关联属性
  public tenant?: Tenant;
  public department?: Department;
  public role?: Role;

  isActive(): boolean {
    return this.status === 'active';
  }

  isSuperAdmin(): boolean {
    return this.type === 'super_admin';
  }

  toSafeObject(): any {
    const { passwordHash, ...safeData } = this.toJSON();
    return safeData;
  }

  /**
   * 获取用户完整名称
   */
  getFullName(): string {
    if (this.firstName && this.lastName) {
      return `${this.lastName} ${this.firstName}`;
    }
    return this.firstName || this.lastName || this.email;
  }
}

User.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    avatar: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    passwordHash: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'password_hash',
    },
    firstName: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'first_name',
    },
    lastName: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'last_name',
    },
    type: {
      type: DataTypes.ENUM('super_admin', 'tenant_admin', 'tenant_user'),
      allowNull: false,
      defaultValue: 'tenant_user',
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'suspended'),
      allowNull: false,
      defaultValue: 'active',
    },
    roleId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'role_id',
    },
    departmentId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'department_id',
    },
    lastLoginAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'last_login_at',
    },
    lastLoginIp: {
      type: DataTypes.STRING(45),
      allowNull: true,
      field: 'last_login_ip',
    },
  },
  {
    sequelize,
    tableName: 'users',
    underscored: true,
    paranoid: true,
    timestamps: true,
    hooks: {
      beforeCreate: async (user: any) => {
        if (user.password) {
          user.passwordHash = await hashPassword(user.password);
        }
      },
      beforeUpdate: async (user: any) => {
        if (user.changed('password') && user.password) {
          user.passwordHash = await hashPassword(user.password);
        }
      },
    },
  },
);

export default User;

